﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.IO;

namespace Avanade.ViddlerDotNet
{
    public class ViddlerSerializationException : ViddlerException
    {
        private Stream stream;

        public ViddlerSerializationException(
            Exception ex, Stream stream)
            : base(-1, ex.Message)
        {
            this.stream = stream;
            this.stream.Position = 0;
        }

        public void ToFile(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            FileStream fileStream = File.OpenWrite(path);

            // Use 4096 for the buffer
            byte[] buffer = new byte[4096];

            int bytesRead = 0;
            // Loop through whole stream and output it to the file
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fileStream.Write(buffer, 0, bytesRead);
                fileStream.Flush();
            }

            fileStream.Close();

            // Reset the position of the original stream
            stream.Position = 0;
        }
    }
}
